package com.promise.jokerdream

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.webkit.WebView
import android.util.Log
import androidx.activity.compose.BackHandler
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.LocalIndication
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.view.WindowCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.rememberNavController
import com.promise.jokerdream.navigation.AppNavGraph
import com.promise.jokerdream.navigation.AppRoute
import com.promise.jokerdream.viewmodel.MainViewModel
import com.promise.jokerdream.network.HttpApiConstants
import com.promise.jokerdream.ui.theme.NoRippleIndication
import com.promise.jokerdream.ui.theme.JokerDreamTheme
import com.promise.jokerdream.utils.AppContext

class MainActivity : ComponentActivity() {
    
    companion object {
        // 编译时确定的URL，可以根据需要修改
        const val DEFAULT_URL = HttpApiConstants.PhoneUrls.home
//        const val DEFAULT_URL = "https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=102067279&redirect_uri=https%3A%2F%2Fdld.qzapp.z.qq.com%2Findex.php&scope=all"
    }
    
    private var webViewInstance: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // AppContext 已在 JokerDreamApplication 中初始化

        // 启用边到边显示，让内容延伸到状态栏和导航栏后面
        WindowCompat.setDecorFitsSystemWindows(window, false)
        // 状态栏/导航栏：透明并使用深色图标，避免与浅色主题冲突
        try {
            val controller = WindowCompat.getInsetsController(window, window.decorView)
            controller.isAppearanceLightStatusBars = true
            controller.isAppearanceLightNavigationBars = true
        } catch (_: Exception) { }
        
        // 获取从外部传入的URL
        val intentUrl = intent.data?.toString()
        val initialUrl = intentUrl ?: DEFAULT_URL
        
        
        setContent {
            JokerDreamTheme {
                CompositionLocalProvider(LocalIndication provides NoRippleIndication) {
                    WebViewApp(
                        initialUrl = initialUrl,
                        onWebViewCreated = { webView ->
                            webViewInstance = webView
                        }
                    )
                }
            }
        }
    }
    
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        
        // 处理新的Intent，确保在主线程更新WebView的URL
        intent?.data?.toString()?.let { newUrl ->
            Log.d("MainActivity", "onNewIntent接收新URL: $newUrl")
            runOnUiThread {
                webViewInstance?.loadUrl(newUrl)
            }
        }
    }
}

@Composable
fun WebViewApp(
    initialUrl: String = MainActivity.DEFAULT_URL,
    onWebViewCreated: (WebView) -> Unit = {}
) {
    val context = LocalContext.current
    val navController = rememberNavController()
    val viewModel: MainViewModel = viewModel()
    
    // 处理返回手势
    BackHandler {
        if (!navController.popBackStack()) {
            // 如果导航栈无法返回，则返回桌面
            (context as? ComponentActivity)?.moveTaskToBack(true)
        }
    }
    
    // 监听URL变化，当外部传入新URL时更新WebView
    LaunchedEffect(initialUrl) {
        viewModel.loadUrl(initialUrl)
    }
    
    // 使用导航图
    AppNavGraph(
        navController = navController,
        startDestination = AppRoute.Main.route,
        onWebViewCreated = onWebViewCreated,
        viewModel = viewModel
    )
}

